//
//  SALoginController.m
//  ShopAssistant
//
//  Created by FangGeek on 2017/11/16.
//  Copyright © 2017年 hyxt. All rights reserved.
//

#import "SALoginController.h"
#import "GPRegularExpression.h"
#import "JKCountDownButton.h"
#import "SAHomeController.h"
#import "SALeftMenuController.h"
#import "XLSlideMenu.h"
#import "SAShopListSelectController.h"

@interface SALoginController ()<UITextFieldDelegate>
@property (strong, nonatomic) IBOutlet UIView *phoneView;
@property (weak, nonatomic) IBOutlet UIView *codeView;
@property (weak, nonatomic) IBOutlet JKCountDownButton *codeBtn;
@property (weak, nonatomic) IBOutlet UIButton *okBtn;
@property (weak, nonatomic) IBOutlet UITextField *phoneTextFiled;
@property (weak, nonatomic) IBOutlet UITextField *codeTextFiled;

@end

@implementation SALoginController

- (void)viewDidLoad
{
    [super viewDidLoad];
    
    [self bulidUI];
    
    [self.phoneTextFiled addTarget:self action:@selector(textFieldDidChange:) forControlEvents:UIControlEventEditingChanged];
    [self.codeTextFiled addTarget:self action:@selector(textFieldDidChange:) forControlEvents:UIControlEventEditingChanged];
    
    [self.okBtn setBackgroundColor:SAHEXRGB(0xE53546) forState:UIControlStateNormal];
    [self.okBtn setBackgroundColor:[SAHEXRGB(0xE53546) colorWithAlphaComponent:0.4] forState:UIControlStateDisabled];

    
    if ([SAUserDefaults objectForKey:@"SAPhone"])
    {
        [MBProgressHUD showMessage:@"请稍后..."];
        
        [self loginRequsetWithPhone:[SAUserDefaults objectForKey:@"SAPhone"]];
    }
    
}

-(void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    
    [self.navigationController setNavigationBarHidden:YES animated:YES];
    
}

- (void)bulidUI
{
    self.phoneView.layer.cornerRadius = self.codeView.layer.cornerRadius = self.okBtn.layer.cornerRadius = 20;
    self.phoneView.layer.borderWidth = self.codeView.layer.borderWidth = self.codeBtn.layer.borderWidth = 0.3;
    self.phoneView.layer.borderColor = self.codeView.layer.borderColor =  SAHEXRGB(0x999999).CGColor;
    self.codeBtn.layer.borderColor = SAHEXRGB(0xE53546).CGColor;
    self.codeBtn.layer.cornerRadius = 15;

    
}

- (void)textFieldDidChange:(UITextField *)textField {
    
    if (self.phoneTextFiled.text.length == 11 && self.codeTextFiled.text.length == 6 )
    {
        self.okBtn.enabled = YES;
    }
    else
    {
        self.okBtn.enabled = NO;
    }
    
}

- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string {
    NSString * new_text_str = [textField.text stringByReplacingCharactersInRange:range withString:string];
    if (textField == self.phoneTextFiled)
    {
        if (new_text_str.length > 11)
        {
            return NO;
        }
    }
    else
    {
        if (new_text_str.length > 6)
        {
            return NO;
        }
    }
    
    return YES;
}
- (IBAction)okAction:(id)sender
{
    if (![GPRegularExpression regularExpressionWithMobileNumber:self.phoneTextFiled.text])
    {
        [UIAlertView showWithTitle:@"提示" message:@"请输入正确的手机号" cancelButtonTitle:nil otherButtonTitles:@[@"我知道了"] tapBlock:nil];
        return;
    }
    [MBProgressHUD showMessage:@"请稍候..."];
    
    [SAHttpApi requestBindPhoneWithPhone:self.phoneTextFiled.text WithMessageCode:self.codeTextFiled.text WithComeBack:^(NSDictionary *object, NSError *error) {
        if (!error)
        {
            
            if ([object[@"status"] integerValue] == 1)
            {
                if ([object[@"content"] integerValue] == 1)
                {
                    [SAUserDefaults setObject:self.phoneTextFiled.text forKey:@"SAPhone"];
                    
                    [self loginRequsetWithPhone:self.phoneTextFiled.text];
                }
                else
                {
                    [MBProgressHUD hideHUD];
                    [MBProgressHUD showError:@"绑定失败"];
                }
            }
            else
            {
                [MBProgressHUD hideHUD];
                [MBProgressHUD showError:object[@"msg"]];
                
            }
        }
        else
        {
            [MBProgressHUD hideHUD];
            [UIAlertView showWithTitle:@"提示" message:@"请检查网络设置,稍后再试.." cancelButtonTitle:nil otherButtonTitles:@[@"我知道了"] tapBlock:nil];
            
        }
    }];
    
    
}

- (IBAction)codeAction:(JKCountDownButton *)sender
{
    if (![GPRegularExpression regularExpressionWithMobileNumber:self.phoneTextFiled.text])
    {
        [UIAlertView showWithTitle:@"提示" message:@"请输入正确的手机号" cancelButtonTitle:nil otherButtonTitles:@[@"我知道了"] tapBlock:nil];
        return;
    }
    
    [SAHttpApi requestCheakPhoneWithPhone:self.phoneTextFiled.text WithComeBack:^(NSDictionary *object, NSError *error) {
        if (!error)
        {
            if ([object[@"status"] integerValue] == 1)
            {
                [SAHttpApi requestGetMessageCodeWithPhone:self.phoneTextFiled.text WithComeBack:^(NSDictionary *object, NSError *error) {
                    if (!error)
                    {
                        if ([object[@"status"] integerValue] == 1)
                        {
                            sender.enabled = NO;
                            //button type要 设置成custom 否则会闪动
                            [sender startCountDownWithSecond:60];
                            
                            [sender countDownChanging:^NSString *(JKCountDownButton *countDownButton,NSUInteger second) {
                                NSString *title = [NSString stringWithFormat:@"剩余%zd秒",second];
                                countDownButton.layer.borderColor = SAHEXRGB(0x999999).CGColor;
                                return title;
                            }];
                            [sender countDownFinished:^NSString *(JKCountDownButton *countDownButton, NSUInteger second) {
                                countDownButton.enabled = YES;
                                countDownButton.layer.borderColor = SAHEXRGB(0xE53546).CGColor;
                                return @"点击重新获取";
                                
                            }];
                            [MBProgressHUD showText:@"验证码已发送"];
                        }
                        else
                        {
                            [MBProgressHUD showError:object[@"msg"]];
                        }
                    }
                    else
                    {
                        [UIAlertView showWithTitle:@"提示" message:@"请检查网络设置,稍后再试.." cancelButtonTitle:nil otherButtonTitles:@[@"我知道了"] tapBlock:nil];
                        
                    }
                    
                }];
            }
            else
            {
                [MBProgressHUD showError:object[@"msg"]];
                
            }
            
        }
        else
        {
            
            [UIAlertView showWithTitle:@"提示" message:@"请检查网络设置,稍后再试.." cancelButtonTitle:nil otherButtonTitles:@[@"我知道了"] tapBlock:nil];
        }
    }];
    
    
    
}

-(void)touchesEnded:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event
{
    [UITextField AllResignFirstResponder];
    
}


#pragma mark - 请求

- (void)loginRequsetWithPhone:(NSString *)phone
{
    [SAHttpApi requestListWithPhone:phone WithComeBack:^(NSDictionary *object, NSError *error) {
        
        if (!error)
        {
            if ([object[@"status"] integerValue] == 1)
            {
                NSArray *shopList = object[@"content"];
                if (shopList.count == 0)
                {
                    [MBProgressHUD hideHUD];
                    [UIAlertView showWithTitle:@"提示" message:@"你尚未加入任何店铺,请联系企业" cancelButtonTitle:nil otherButtonTitles:@[@"我知道"] tapBlock:nil];
                }
                else
                {
                    
                    NSArray *tempArr =  [shopList filteredArrayUsingPredicate:[NSPredicate predicateWithFormat:@"shopId = %@",[SAUserDefaults objectForKey:@"SAShopId"]]];
                    if (shopList.count == 1||(shopList.count > 1 && tempArr.count > 0))
                    {
                        NSDictionary *tempDict = tempArr.count > 0?tempArr.firstObject:shopList.firstObject;
      
                        [SAHttpApi requestGetUserInfoWithPhone:phone WithShopId:tempDict[@"shopId"] WithComeBack:^(NSDictionary *object, NSError *error) {
                            if (!error)
                            {
                                if ([object[@"status"] integerValue] == 1)
                                {
                                    SAUserInfoModel *model = [SAUserInfoModel mj_objectWithKeyValues:object[@"content"]];
                                    [SAUserInfoManager sharedSAUserInfoManager].model = model;
                                    [SAUserInfoManager sharedSAUserInfoManager].model._id = object[@"content"][@"id"];
                                    [SAUserInfoManager sharedSAUserInfoManager].model.row = [[SAUserDefaults objectForKey:model.shopId] integerValue];
                                    [[SAUserInfoManager sharedSAUserInfoManager] saveLoginInfo];
                                    
                                    [SAHttpApi requestGetHTTPURLWithNumber:[[SAUserDefaults objectForKey:model.shopId] integerValue] != 0 ?[NSString stringWithFormat:@"%@",[SAUserDefaults objectForKey:model.shopId]]:([model.identityCollect isEqualToString:@"2"]?@"1":@"2") WithEmpId:[SAUserInfoManager sharedSAUserInfoManager].model._id WithAppTo:[SAUserInfoManager sharedSAUserInfoManager].model.identityCollect WithComeBack:^(NSDictionary *object, NSError *error) {
                                        if (!error)
                                        {
                                            
                                            if ([object[@"status"] integerValue] == 1)
                                            {
                                                [MBProgressHUD hideHUD];
                                                
                                                SAHomeController *vc = [[SAHomeController alloc] init];
                                                vc.urlString = object[@"content"];
                                                SANavigationController *nav = [[SANavigationController alloc] initWithRootViewController:vc];
                                                
                                                //左侧菜单
                                                //左侧菜单
                                                SALeftMenuController *leftVC = [[SALeftMenuController alloc] init];
                                                //创建滑动菜单
                                                XLSlideMenu *slideMenu = [[XLSlideMenu alloc] initWithRootViewController:nav];
                                                //设置左右菜单
                                                slideMenu.leftViewController = leftVC;
                                            
                                                [UIApplication sharedApplication].keyWindow.rootViewController = slideMenu;
                                                
                                            }
                                            else
                                            {
                                                [MBProgressHUD hideHUD];
                                                [MBProgressHUD showError:object[@"msg"]];
                                                
                                            }
                                        }
                                        else
                                        {
                                            [MBProgressHUD hideHUD];
                                            [UIAlertView showWithTitle:@"提示" message:@"请检查网络设置,稍后再试.." cancelButtonTitle:nil otherButtonTitles:@[@"我知道了"] tapBlock:nil];
                                        }
                                    }];
                                    
                                }
                                else
                                {
                                    [MBProgressHUD hideHUD];
                                    [MBProgressHUD showError:object[@"msg"]];
                                    
                                }
                            }
                            else
                            {
                                [MBProgressHUD hideHUD];
                                [UIAlertView showWithTitle:@"提示" message:@"请检查网络设置,稍后再试.." cancelButtonTitle:nil otherButtonTitles:@[@"我知道了"] tapBlock:nil];
                                
                            }
                        }];
                        
                    }
                    else
                    {
                        
                        SAShopListSelectController *vc = [[SAShopListSelectController alloc] init];
                        vc.datas = shopList;
                        [self.navigationController pushViewController:vc animated:YES];
                        [MBProgressHUD hideHUD];
                    }
                    
                    
                }
            }
            else
            {
                [MBProgressHUD hideHUD];
                [MBProgressHUD showError:object[@"msg"]];
                
            }
        }
        else
        {
            [MBProgressHUD hideHUD];
            [UIAlertView showWithTitle:@"提示" message:@"请检查网络设置,稍后再试.." cancelButtonTitle:nil otherButtonTitles:@[@"我知道了"] tapBlock:nil];
        }
    }];
    
}
@end
